#include "stdafx.h"
#include "FlexFile.h"

PFLEXFILEHEADER CreateFlexFile()
{
	PFLEXFILEHEADER header = new FLEXFILEHEADER;
	memset( header, 0, sizeof(*header) );
	return header;
}

void DestroyFlexFile( PFLEXFILEHEADER header )
{
	delete header;
}

PFLEXFILEHEADER AppendFlexEntity( PFLEXFILEHEADER header, const char* entity, long entitySize )
{
	PFLEXFILEENTRY entry = (PFLEXFILEENTRY)(header+1);

	long oldSize = sizeof(FLEXFILEHEADER) + sizeof(FLEXFILEENTRY) * header->count + header->d[8];
	long newSize = oldSize + sizeof(FLEXFILEENTRY) + entitySize;

	PFLEXFILEHEADER newHeader = (PFLEXFILEHEADER)new char[newSize];
	PFLEXFILEENTRY newEntry = (PFLEXFILEENTRY)(newHeader+1);

	memcpy( newHeader, header, sizeof(FLEXFILEHEADER) );

	for ( long i = 0; i < header->count; i++ )
	{
		newEntry->offset = entry->offset + sizeof(FLEXFILEENTRY);
		newEntry->size = entry->size;
		entry++;
		newEntry++;
	}

	newEntry->offset = newSize - entitySize;
	newEntry->size = entitySize;

	char* p = (char*)(newEntry+1);
	memcpy( p, (char*)entry, header->d[8] );
	memcpy( p + header->d[8], entity, entitySize );

	newHeader->count = header->count + 1;
	newHeader->d[8] = header->d[8] + entitySize;

	delete header;
	return newHeader;
}

char* GetFlexArchiveFile( PFLEXFILEHEADER header, const char* targetName, long* fileLength )
{
	PFLEXARCHIVEFILE archive;
	PFLEXFILEENTRY entry = (PFLEXFILEENTRY)(header+1);
	for ( int i = 0; i < header->count; i++ )
	{
		archive = NULL;
		if ( entry->size !=0 && entry->offset != 0 )
		{
			archive = (PFLEXARCHIVEFILE)((char*)header + entry->offset);
			if ( _stricmp( archive->filename, targetName ) == 0 )
				break;
		}
		entry++;
	}

	if ( !archive )
		return NULL;

	*fileLength = entry->size - sizeof(FLEXARCHIVEFILE) - 1;

	return archive->content;
}
